﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Interop;
using Autodesk.AutoCAD.Internal;
using DYH.Extensions.CAD.Service;
using Wpf.Ui.Appearance;
using Wpf.Ui.Controls;
using Application = Autodesk.AutoCAD.ApplicationServices.Core.Application;
using MessageBox = Wpf.Ui.Controls.MessageBox;
using MouseEventArgs = System.Windows.Input.MouseEventArgs;

namespace DYH.Extensions.CAD.Wpf;

/// <summary>
/// 提供WPF窗口管理工具方法
/// </summary>
public static class WpfManager
{
    /// <summary>
    /// 静态构造函数，初始化默认主题为深色模式
    /// </summary>
    static WpfManager()
    {
        // ReSharper disable once RedundantArgumentDefaultValue
        ApplicationThemeManager.Apply(ApplicationTheme.Dark, kWindowBackdropType,
            updateAccent: false);
    }

    /// <summary>
    /// 显示临时窗口，需要通过using语句释放资源
    /// </summary>
    /// <typeparam name="T">窗口类型</typeparam>
    /// <returns>WpfTempManager实例</returns>
    public static WpfTempManager ShowTempWindow<T>() where T : Window
    {
        return new WpfTempManager(typeof(T));
    }

    /// <summary>
    /// 以模态方式显示窗口
    /// </summary>
    /// <param name="window">要显示的窗口</param>
    /// <returns>对话框结果</returns>
    public static bool? ShowDialog(Window window)
    {
        InitWpfUi(window);
        window.RegisterCloseMessage();
        var result = Application.ShowModalWindow(Acap.MainWindow.Handle, window, false);
        return result;
    }

    /// <summary>
    /// 以非模态方式显示窗口
    /// </summary>
    /// <param name="window">要显示的窗口</param>
    public static void Show(Window window)
    {
        InitWpfUi(window);
        window.RegisterCloseMessage();
        Acap.ShowModelessWindow(Acap.MainWindow.Handle, window, false);
    }

    private const WindowBackdropType kWindowBackdropType = WindowBackdropType.Mica;

    /// <summary>
    /// 初始化WPF控件的UI样式
    /// </summary>
    /// <param name="frameworkElement">需要初始化的控件</param>
    private static void InitWpfUi(this FrameworkElement frameworkElement)
    {
        if (frameworkElement is FluentWindow fluentWindow)
        {
            fluentWindow.ExtendsContentIntoTitleBar = true;
            fluentWindow.WindowBackdropType = kWindowBackdropType;
        }

        ApplicationThemeManager.Apply(frameworkElement);
    }

    /// <summary>
    /// 显示消息框
    /// </summary>
    /// <param name="message">消息内容</param>
    /// <param name="title">消息框标题</param>
    public static void ShowMessageBox(string message, string title = "")
    {
        var messageBox = new MessageBox()
        {
            Content = message, Title = title, CloseButtonText = "确认"
        };
        InitWpfUi(messageBox);
        Application.ShowModalWindow(messageBox);
    }
}

/// <summary>
/// 管理临时WPF窗口的类
/// </summary>
public sealed class WpfTempManager : IDisposable
{
    private static readonly Dictionary<string, Window> _tempWindowNames = new();

    /// <summary>
    /// 构造函数，创建或显示指定类型的临时窗口
    /// </summary>
    /// <param name="windowType">窗口类型</param>
    public WpfTempManager(Type windowType)
    {
        var key = SystemVariableManager.CmdNames + "|" + windowType.Name;
        if (!_tempWindowNames.ContainsKey(key))
        {
            if (AppHelper.Get(windowType) is Window newWindow)
            {
                newWindow.Closing += WindowOnClosing;
                newWindow.Closed += (_, _) => { _tempWindowNames.Remove(key); };
                newWindow.MouseLeave -= WindowOnMouseLeave;
                newWindow.MouseLeave += WindowOnMouseLeave;
                _tempWindowNames[key] = newWindow;
            }
        }

        _tempWindowNames.TryGetValue(key, out _window);
        if (_window is not null)
        {
            WpfManager.Show(_window);
        }

        Utils.SetFocusToDwgView();
    }

    private static void WindowOnClosing(object sender, CancelEventArgs e)
    {
        if (sender is not Window window)
            return;
        e.Cancel = true;
        window.Hide();
    }

    private readonly Window? _window;

    private void WindowOnMouseLeave(object sender, MouseEventArgs e)
    {
        Utils.SetFocusToDwgView();
    }

    /// <summary>
    /// 获取或设置是否已释放资源
    /// </summary>
    public bool IsDisposed { get; private set; }

    /// <summary>
    /// 释放临时窗口资源
    /// </summary>
    public void Dispose()
    {
        if (IsDisposed)
            return;
        if (_window is not null)
        {
            var windowInteropHelper = new WindowInteropHelper(_window);
            if (windowInteropHelper.Handle != IntPtr.Zero)
            {
                _window.Hide();
            }
        }

        IsDisposed = true;
    }
}